package com.ktgj.customer.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.ktgj.common.core.annotation.Excel;
import com.ktgj.common.core.constant.InsuranceTypeEnum;
import com.ktgj.common.core.enums.EmHelper;
import com.ktgj.common.core.utils.DateCalcUtils;
import com.ktgj.common.core.utils.helper.StringHelper;
import com.ktgj.customer.common.*;
import com.ktgj.customer.domain.*;
import com.ktgj.customer.domain.Insurance.*;
import com.ktgj.customer.domain.Insurance.dftModel.BuyInsuranceInfo;
import com.ktgj.customer.domain.Insurance.dftModel.BuyInsuranceInput;
import com.ktgj.customer.domain.Insurance.dftModel.BuyInsuranceOutput;
import com.ktgj.customer.domain.Insurance.heydayModel.HeydayUrlInfo;
import com.ktgj.customer.domain.Insurance.hlModel.*;
import com.ktgj.customer.domain.Insurance.hlModel.Insurance;
import com.ktgj.customer.domain.vo.*;
import com.ktgj.customer.domain.vo.ProductVo;
import com.ktgj.customer.mapper.*;
import com.ktgj.customer.service.ICustomerService;
import com.ktgj.customer.service.IFinanceAutobillExceptionService;
import com.ktgj.customer.service.IInsuranceRecordService;
import com.ktgj.customer.util.PublicClass;
import com.ktgj.customer.util.SysUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class InsuranceRecordServiceImpl implements IInsuranceRecordService
{
    @Autowired
    private CustomerMapper customerMapper;

    @Autowired
    private AssistProductMapper assistProductMapper;

    @Autowired
    private InsuranceTypeMapper insuranceTypeMapper;

    @Autowired
    private InsuranceRecordMapper insuranceRecordMapper;

    @Autowired
    private GuaranteeMapper guaranteeMapper;

    @Autowired
    private ICustomerService customerService;

    @Autowired
    private CustomerCardMapper customerCardMapper;

    @Autowired
    private InsuranceCompanyMapper insuranceCompanyMapper;

    /**
     * 新增保险记录
     * */
    @Transactional
    @Override
    public InsuranceReturnVo insertInsuranceRecord(Long customerId, ProductVo productVo) throws Exception
    {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm");
        SimpleDateFormat time = new SimpleDateFormat("HH:mm:ss");
        InsuranceReturnVo insuranceReturnVo = new InsuranceReturnVo();
        Date date = new Date();
        //获取会员信息
        if (customerId == null || customerId == 0)
        {
            throw new Exception("会员id不能为空");
        }
        Customer customer = customerMapper.selectCustomerById(customerId);
        if (customer == null)
        {
            throw new Exception("无效的会员id");
        }

        //获取会员卡号
        CustomerIdVo customerIdVo = new CustomerIdVo();
        customerIdVo.setCustomerId(customerId);
        customerIdVo = customerService.customerId(customerIdVo);

        Long insuranceTypeId = null;
        AssistProduct assistProduct = null;
        if (productVo.insuranceTypeId != null)
        {
            insuranceTypeId = productVo.insuranceTypeId;
        } else
        {
            //获取辅营产品信息
            if (productVo.id == null || productVo.id == 0)
            {
                throw new Exception("辅营产品id不能为空");
            }
            assistProduct = assistProductMapper.selectProduct(productVo.id);
            if (assistProduct == null)
            {
                throw new Exception("无效的辅营产品id");
            }
            //获取产品类型
            if (assistProduct.getProductTypeid() == null || assistProduct.getProductTypeid() == 0)
            {
                throw new Exception("辅营产品对应产品类型ID不能为空");
            }
            insuranceTypeId = assistProduct.getProductTypeid();
        }
        InsuranceType insuranceType = insuranceTypeMapper.selectInsuranceTypeById(insuranceTypeId);
        if (insuranceType == null)
        {
            throw new Exception("无效的产品类型id");
        }
        if (insuranceType.getCompanyId() == null || insuranceType.getCompanyId() == 0)
        {
            throw new Exception("产品类型对应保险公司id不能为空");
        }
        if (insuranceType.getInsTypeCode() == null || insuranceType.getInsTypeCode().equals(""))
        {
            throw new Exception("产品类型代码不能为空");
        }

        Long guaranteeId = System.currentTimeMillis() / 1000;

        //保险类型为航联(随卡)
        if (insuranceType.getInsTypeCode().equals(InsuranceTypeEnum.HangLian.getValue()))
        {
            //获取会员指定保险类型和保险公司的开保记录
            List<InsuranceRecord> insuranceRecordList = insuranceRecordMapper.selInsuranceRecordList(customerId, insuranceType.getInsTypeId(), insuranceType.getCompanyId());
            //符合继续开保条件
            if (insuranceRecordList == null || insuranceRecordList.size() < 2)
            {
                //航联参数赋值
                HLInsurance hlInsurance = hanglianParameter(productVo, customer, insuranceType);
                //航联开保
                Auis auis = hanglianUtils(hlInsurance);

                Guarantee guarantee = new Guarantee();
                guarantee.setGuaranteeId(guaranteeId);
                if (auis.getResponseData() != null &&
                        auis.getResponseData().getPolicyInfo().getPolicyNo() != null &&
                        !auis.getResponseData().getPolicyInfo().getPolicyNo().equals(""))
                {
                    guarantee.setGuaranteeNo(auis.getResponseData().getPolicyInfo().getPolicyNo());
                }
                if (productVo.id != null)
                {
                    guarantee.setAssistProductId(productVo.id);
                }
                guarantee.setCardId(productVo.cardNum);
                guarantee.setCustomerId(customerId);
                guarantee.setInsTypeId(insuranceTypeId);
                guarantee.setInsCoId(insuranceType.getCompanyId());
                //航联开保成功
                if (auis.getResponseData() != null &&
                        auis.getResponseData().getPolicyInfo().getPolicyNo() != null &&
                        !auis.getResponseData().getPolicyInfo().getPolicyNo().equals(""))
                {
                    guarantee.setGuaranteeStatus(InsuranceTypeEnum.Open.getValue());
                    guarantee.setExportstate(InsuranceTypeEnum.Open.getValue());
                    guarantee.setPaydate(date);
                }
                //航联开保失败
                else
                {
                    guarantee.setGuaranteeStatus(InsuranceTypeEnum.FailedToActivate.getValue());
                    guarantee.setExportstate(InsuranceTypeEnum.FailedToActivate.getValue());
                }
                guarantee.setSaleGuaranteeTime(date);
                if (auis.getResponseData() != null)
                {
                    guarantee.setPayaccountnumber(auis.getResponseData().getSerialNumber());
                }
                guarantee.setAmount(insuranceType.getPrice());
                guarantee.setPayorderid(productVo.orderNum);
                guarantee.setPayaccountnumber("q1");
                guarantee.setMerid("2021072000010716");
                guarantee.setPayresultcode(1l);
                guarantee.setBankid(productVo.paymentChannel);
                guarantee.setCreatetime(date);
                guarantee.setExtjson(JSONObject.toJSONString(auis));
                String birthday = customer.getCustCertificateNo().substring(6, 10);
                birthday = birthday + "-" + customer.getCustCertificateNo().substring(10, 12);
                birthday = birthday + "-" + customer.getCustCertificateNo().substring(12, 14);
                guarantee.setBirthday(birthday);
                guarantee.setSex(customer.getCustomerSex());
                guarantee.setCertificateType(customer.getIdType());
                guarantee.setLicenseNumber(customer.getCustCertificateNo());
                guarantee.setPhone(customer.getContractPhoneOne());
                guarantee.setMembership("法定");
                int i = guaranteeMapper.insertGuarantee(guarantee);
                if (i <= 0)
                {
                    throw new Exception("保险记录添加失败");
                } else
                {
                    InsuranceRecord insuranceRecord = new InsuranceRecord();
                    insuranceRecord.setCustomerCard(productVo.cardNum);
                    insuranceRecord.setReturnData(auis.toString());
                    insuranceRecord.setBatch(auis.getRequestId());
                    insuranceRecord.setInsTypeId(insuranceTypeId);
                    insuranceRecord.setCustomerId(customerId);
                    insuranceRecord.setEmployeeId(10l);
                    insuranceRecord.setInsCoId(insuranceType.getCompanyId());
                    insuranceRecord.setIdTypeId(customer.getIdType());
                    insuranceRecord.setInsCoverName(format.format(date));

                    int count = Integer.parseInt(format.format(date).substring(8, 10)) + 1;
                    String tmpCount = String.valueOf(count);
                    if (tmpCount.length() == 1)
                    {
                        tmpCount = "0" + tmpCount;
                    }

                    String insuranceStartDate = format.format(date).substring(0, 8) + tmpCount + " 00:00:00";

                    insuranceRecord.setInsValidDate(format.parse(insuranceStartDate));

                    int parseInt = Integer.parseInt(format.format(date).substring(0, 4));
                    parseInt = parseInt + 1;
                    String insuranceEndDate = parseInt + format.format(date).substring(4, 10) + " 23:59:59";

                    insuranceRecord.setInsInvalidDate(format.parse(insuranceEndDate));
                    insuranceRecord.setInsured(customer.getCustomerName());
                    insuranceRecord.setBeneficiary(customer.getCustomerName());
                    if (auis.getResponseData() != null &&
                            auis.getResponseData().getPolicyInfo().getPolicyNo() != null &&
                            !auis.getResponseData().getPolicyInfo().getPolicyNo().equals(""))
                    {
                        insuranceRecord.setInsMemo("已开通成功");
                        insuranceRecord.setHLurl(auis.getResponseData().getPolicyInfo().getEPolicyUrl());
                        insuranceRecord.setOpenState(InsuranceTypeEnum.Open.getValue());
                    } else
                    {
                        insuranceRecord.setInsMemo("开通失败");
                        insuranceRecord.setOpenState(InsuranceTypeEnum.FailedToActivate.getValue());
                    }
                    if (auis.getResponseData() != null &&
                            auis.getResponseData().getPolicyInfo().getPolicyNo() != null &&
                            !auis.getResponseData().getPolicyInfo().getPolicyNo().equals(""))
                    {
                        insuranceRecord.setInsSlipNo(auis.getResponseData().getPolicyInfo().getPolicyNo());
                    }
                    insuranceRecord.setOperationTime(time.format(date));
                    insuranceRecord.setInsCertificateNo(customer.getCustCertificateNo());
                    insuranceRecord.setMobilephone(customer.getContractPhoneOne());
                    insuranceRecord.setOrderNum(productVo.orderNum);
                    insuranceRecord.setOrderSource(productVo.orderSource);
                    insuranceRecord.setGuaranteeId(guaranteeId);
                    insuranceRecord.setBatch(JSON.toJSONString(productVo));
                    insuranceRecordMapper.insertInsuranceRecord(insuranceRecord);
                    if (auis.getResponseData() != null &&
                            auis.getResponseData().getPolicyInfo().getPolicyNo() != null &&
                            !auis.getResponseData().getPolicyInfo().getPolicyNo().equals(""))
                    {
                        insuranceReturnVo.setSuccess(true);
                        insuranceReturnVo.setMsg("成功");
                    } else
                    {
                        insuranceReturnVo.setSuccess(false);
                        insuranceReturnVo.setMsg("失败");
                    }
                    return insuranceReturnVo;
                }
            }
            //开保数量已达上限
            else
            {
                Guarantee guarantee = new Guarantee();
                guarantee.setGuaranteeId(guaranteeId);
                if (productVo.id != null)
                {
                    guarantee.setAssistProductId(productVo.id);
                }
                guarantee.setCardId(productVo.cardNum);
                guarantee.setBrieflyguaranteeDate(date);
                guarantee.setAmount(insuranceType.getPrice());
                guarantee.setBrieflyguaranteeEmployeeId(10l);
                guarantee.setCustomerId(customerId);
                guarantee.setInsTypeId(insuranceTypeId);
                guarantee.setInsCoId(insuranceType.getCompanyId());
                guarantee.setGuaranteeStatus(InsuranceTypeEnum.Suspend.getValue());
                guarantee.setExportstate(InsuranceTypeEnum.Suspend.getValue());
                guarantee.setPayresultcode(1l);
                guarantee.setBankid(productVo.paymentChannel);
                guarantee.setPaydate(date);
                guarantee.setCreatetime(date);

                guarantee.setCertificateType(customer.getIdType());
                if (customer.getIdType() != null && customer.getIdType().equals(EmHelper.CertificateType.ID_CARD.getValue()))
                {
                    if (customer.getCustCertificateNo() != null)
                    {
                        boolean flag = PublicClass.CheckIDCard(customer.getCustCertificateNo());
                        if (!flag)
                        {
                            throw new Exception("请使用正确的证件号");
                        }
                    } else
                    {
                        throw new Exception("请完善会员证件号信息");
                    }
                    guarantee.setLicenseNumber(customer.getCustCertificateNo());
                    String birthday = customer.getCustCertificateNo().substring(6, 10);
                    birthday = birthday + "-" + customer.getCustCertificateNo().substring(10, 12);
                    birthday = birthday + "-" + customer.getCustCertificateNo().substring(12, 14);
                    guarantee.setBirthday(birthday);
                } else
                {
                    guarantee.setLicenseNumber(customer.getCustCertificateNo());
                    guarantee.setBirthday(format.format(customer.getBirthday()));
                }
                guarantee.setSex(customer.getCustomerSex());
                guarantee.setPhone(customer.getContractPhoneOne());
                guarantee.setMembership("法定");
                if (productVo.id != null)
                {
                    guarantee.setAssistProductId(productVo.id);
                }
                guarantee.setBusinessSource(productVo.orderSource);
                guarantee.setCustomerCard(productVo.cardNum);
                guarantee.setProductCode(insuranceType.getProduct());
                int i = guaranteeMapper.insertGuarantee(guarantee);
                if (i <= 0)
                {
                    insuranceReturnVo.setSuccess(false);
                    insuranceReturnVo.setMsg("开保数量达到上限，添加保险信息失败");
                } else
                {
                    insuranceReturnVo.setSuccess(true);
                    insuranceReturnVo.setMsg("开保数量达到上限，已添加保险信息至待开保");
                }
                return insuranceReturnVo;
            }
        }
        //保险类型为德付通（随票）
        else if (insuranceType.getInsTypeCode().equals(InsuranceTypeEnum.Dove.getValue()))
        {
            //德付通开保赋值
            BuyInsuranceInput buyInsuranceInput = buyPolicyNoPay(productVo, insuranceType);
            //德付通开保
            BuyInsuranceOutput buyInsuranceOutput = buyInsurance(buyInsuranceInput);

            guaranteeId = System.currentTimeMillis() / 1000;

            Guarantee guarantee = new Guarantee();
            guarantee.setGuaranteeId(guaranteeId);
            guarantee.setCardId(customerIdVo.getCustomerCard());
            guarantee.setCustomerId(customerId);
            guarantee.setInsTypeId(insuranceType.getInsTypeId());
            guarantee.setInsCoId(insuranceType.getCompanyId());
            guarantee.setGuaranteeNo(buyInsuranceOutput.getInsuranceNo());
            guarantee.setGuaranteeStatus(InsuranceTypeEnum.Initial.getValue());
            guarantee.setExportstate(InsuranceTypeEnum.Initial.getValue());
            guarantee.setSaleGuaranteeTime(date);
            guarantee.setAmount(insuranceType.getPrice());
            guarantee.setPayorderid(productVo.orderNum);
            guarantee.setPayresultcode(1l);
            guarantee.setBankid(productVo.paymentChannel);
            guarantee.setPaydate(date);
            guarantee.setCreatetime(date);
            guarantee.setExtjson(JSONObject.toJSONString(buyInsuranceOutput));
            if (customer.getIdType() != null && customer.getIdType().equals(EmHelper.CertificateType.ID_CARD.getValue()))
            {
                if (customer.getCustCertificateNo() != null)
                {
                    boolean flag = PublicClass.CheckIDCard(customer.getCustCertificateNo());
                    if (!flag)
                    {
                        throw new Exception("请使用正确的证件号");
                    }
                } else
                {
                    throw new Exception("请完善会员证件号信息");
                }
                guarantee.setLicenseNumber(customer.getCustCertificateNo());
                String birthday = customer.getCustCertificateNo().substring(6, 10);
                birthday = birthday + "-" + customer.getCustCertificateNo().substring(10, 12);
                birthday = birthday + "-" + customer.getCustCertificateNo().substring(12, 14);
                guarantee.setBirthday(birthday);
            } else
            {
                guarantee.setLicenseNumber(customer.getCustCertificateNo());
                guarantee.setBirthday(format.format(customer.getBirthday()));
            }
            guarantee.setSex(customer.getCustomerSex());
            guarantee.setCertificateType(customer.getIdType());
            guarantee.setLicenseNumber(customer.getCustCertificateNo());
            guarantee.setPhone(customer.getContractPhoneOne());
            guarantee.setMembership(productVo.relation);
            if (productVo.id != null)
            {
                guarantee.setAssistProductId(productVo.id);
            }
            guarantee.setBusinessSource(productVo.orderSource);
            guarantee.setCustomerCard(customerIdVo.getCustomerCard());
            guarantee.setArriveAirportCode(productVo.arrCity);
            guarantee.setDepartureAirportCode(productVo.depCity);
            guarantee.setProductCode(insuranceType.getProduct());
            int i = guaranteeMapper.insertGuarantee(guarantee);
            if (i <= 0)
            {
                System.out.println("德付通开保日志记录失败");
            }

            InsuranceRecord insuranceRecord = new InsuranceRecord();
            insuranceRecord.setGuaranteeId(guaranteeId);
            insuranceRecord.setCustomerCard(customerIdVo.getCustomerCard());
            insuranceRecord.setMsg(buyInsuranceOutput.getMessage());
            insuranceRecord.setReturnData(buyInsuranceOutput.toString());
            insuranceRecord.setInsTypeId(insuranceTypeId);
            insuranceRecord.setCustomerId(customerId);
            insuranceRecord.setEmployeeId(10l);
            insuranceRecord.setInsCoId(insuranceType.getCompanyId());
            insuranceRecord.setIdTypeId(productVo.insuredIdType);
            insuranceRecord.setInsCoverName(format.format(date));
            try
            {
                String insValidDate = productVo.flightDate;
                insuranceRecord.setInsValidDate(dateFormat.parse(insValidDate));
                insuranceRecord.setInsInvalidDate(simpleDateFormat.parse(productVo.arriveTime));
            } catch (Exception e)
            {
                throw new Exception("日期转换错误");
            }
            insuranceRecord.setInsured(productVo.insuredName);
            insuranceRecord.setBeneficiary(productVo.insuredName);

            if (buyInsuranceOutput.getInsuranceNo() != null)
            {
                insuranceRecord.setInsMemo("开通成功");
                insuranceRecord.setElectronInsNo(buyInsuranceOutput.getInsuranceNo());
                insuranceRecord.setOpenState(InsuranceTypeEnum.Open.getValue());
                insuranceRecord.setInsSlipNo(buyInsuranceOutput.getInsuranceNo());

            } else
            {
                insuranceRecord.setInsMemo("开通失败");
                insuranceRecord.setOpenState(InsuranceTypeEnum.FailedToActivate.getValue());
            }
            insuranceRecord.setOperationTime(format.format(date));
            insuranceRecord.setInsCertificateNo(productVo.insuredId);
            insuranceRecord.setMobilephone(productVo.insuredPhone);
            insuranceRecord.setOrderNum(productVo.orderNum);
            insuranceRecord.setOrderSource(productVo.orderSource);
            insuranceRecord.setBatch(JSON.toJSONString(productVo));
            insuranceRecordMapper.insertInsuranceRecord(insuranceRecord);

            if (buyInsuranceOutput.getInsuranceNo() != null)
            {
                insuranceReturnVo.setMsg("成功");
                insuranceReturnVo.setSuccess(true);
            } else
            {
                insuranceReturnVo.setMsg("失败");
                insuranceReturnVo.setSuccess(false);
            }
            return insuranceReturnVo;
        }
        //保险类型为鼎盛
        else if (insuranceType.getInsTypeCode().equals(InsuranceTypeEnum.HeyDay.getValue()))
        {
            //鼎盛参数赋值
            HeyDayInsuranceVo heyDayInsuranceVo = heydayParameter(productVo, customer);

            String url;
            try
            {
                //鼎盛获取url
                url = HeydayInsurance(productVo.type, heyDayInsuranceVo);
            } catch (Exception e)
            {
                throw new Exception(e.getMessage());
            }

            if (url != null)
            {
                insuranceReturnVo.setMsg("成功");
                insuranceReturnVo.setSuccess(true);
                insuranceReturnVo.setUrl(url);
            } else
            {
                insuranceReturnVo.setMsg("失败");
                insuranceReturnVo.setSuccess(false);
            }
            return insuranceReturnVo;
        } else if (insuranceType.getInsTypeCode().equals(InsuranceTypeEnum.JSSJ.getValue()))
        {
            InsuranceRecord insuranceRecord = new InsuranceRecord();
            insuranceRecord.setGuaranteeId(guaranteeId);
            insuranceRecord.setCustomerCard(customerIdVo.getCustomerCard());
            insuranceRecord.setInsTypeId(insuranceTypeId);
            insuranceRecord.setCustomerId(customerId);
            insuranceRecord.setEmployeeId(10l);
            insuranceRecord.setInsCoId(insuranceType.getCompanyId());
            insuranceRecord.setIdTypeId(customer.getIdType());
            insuranceRecord.setInsCoverName(format.format(date));
            insuranceRecord.setOpenState(InsuranceTypeEnum.Open.getValue());
            insuranceRecord.setInsSlipNo("JSJ" + UUID.randomUUID().toString());
            insuranceRecord.setOperationTime(format.format(date));
            insuranceRecord.setInsCertificateNo(customerIdVo.getLicenseNum());
            insuranceRecord.setMobilephone(productVo.insuredPhone);
            insuranceRecord.setOrderNum(productVo.orderNum);
            insuranceRecord.setOrderSource(productVo.orderSource);
            insuranceRecord.setInsValidDate(date);
            insuranceRecord.setInsInvalidDate(DateCalcUtils.addYear(date, 1));
            insuranceRecord.setBatch(JSON.toJSONString(productVo));
            int rows = insuranceRecordMapper.insertInsuranceRecord(insuranceRecord);
            if (rows > 0)
            {
                Guarantee guarantee = new Guarantee();
                guarantee.setGuaranteeId(guaranteeId);
                guarantee.setCardId(customerIdVo.getCustomerCard());
                guarantee.setCustomerId(customerId);
                guarantee.setInsTypeId(insuranceTypeId);
                guarantee.setInsCoId(insuranceType.getCompanyId());
                guarantee.setGuaranteeStatus(InsuranceTypeEnum.Initial.getValue());
                guarantee.setPayorderid(productVo.orderNum);
                guarantee.setPayresultcode(1l);
                guarantee.setBankid(productVo.paymentChannel);
                guarantee.setPaydate(date);
                guarantee.setCreatetime(date);
                guarantee.setInvalidTime(format.format(DateCalcUtils.addYear(date, 1)));
                int i = guaranteeMapper.insertGuarantee(guarantee);
                if (i <= 0)
                {
                    insuranceReturnVo.setSuccess(false);
                    insuranceReturnVo.setMsg("保险记录添加失败" + productVo.id == null ? "" : productVo.id.toString());
                } else
                {
                    insuranceReturnVo.setSuccess(true);
                    insuranceReturnVo.setMsg("保险记录添加成功");
                }
            }
            return insuranceReturnVo;
        }
        return insuranceReturnVo;
    }


    /**
     * 后端——查询保险记录
     * */
    @Override
    public List<InsuranceRecordVo> backSelectInsuranceRecord(Long customerId) throws Exception {
        if (customerId != null && customerId != 0){
            List<InsuranceRecord> insuranceRecordList = insuranceRecordMapper.backSelectInsuranceRecord(customerId);
            if (insuranceRecordList != null && insuranceRecordList.size() > 0){
                List<InsuranceRecordVo> insuranceRecordVoList = new ArrayList<>();
                for (InsuranceRecord insuranceRecord : insuranceRecordList) {
                    InsuranceRecordVo insuranceRecordVo = new InsuranceRecordVo();
                    insuranceRecordVo.setInsRecordId(insuranceRecord.getInsRecordId());
                    List<CustomerCard> customerCardList = customerCardMapper.CustomerCardList(customerId);
                    for (CustomerCard customerCard : customerCardList) {
                        insuranceRecordVo.setCustomerCard(customerCard.getCardCode());
                        break;
                    }
                    InsuranceType insuranceType = insuranceTypeMapper.selectInsuranceType(insuranceRecord.getInsTypeId());
                    if (insuranceType != null){
                        insuranceRecordVo.setInsType(insuranceType.getInsTypeName());
                    }
                    else {
                        throw new Exception("未查到保险类型");
                    }
                    InsuranceCompany insuranceCompany = insuranceCompanyMapper.insuranceCompany(insuranceRecord.getInsCoId());
                    if (insuranceCompany != null){
                        insuranceRecordVo.setInsCoId(insuranceCompany.getInsCoName());
                    }
                    insuranceRecordVo.setElectronInsNo(insuranceRecord.getInsSlipNo());
                    insuranceRecordVo.setInsCoverName(insuranceRecord.getInsCoverName());
                    insuranceRecordVo.setInsValidDate(insuranceRecord.getInsValidDate());
                    insuranceRecordVo.setInsInvalidDate(insuranceRecord.getInsInvalidDate());
                    insuranceRecordVo.setInsured(insuranceRecord.getInsured());
                    insuranceRecordVo.setInsMemo(insuranceRecord.getInsMemo());
                    insuranceRecordVo.setOperationTime(insuranceRecord.getOperationTime());
                    insuranceRecordVoList.add(insuranceRecordVo);
                }
                return insuranceRecordVoList;
            }
            else {
                throw new Exception("未查到数据");
            }
        }
        else {
            throw new Exception("缺少必要参数");
        }
    }


    /**
     * 航联参数赋值(随卡)
     * */
    public HLInsurance hanglianParameter(ProductVo productVo, Customer customer, InsuranceType insuranceType) throws Exception {
        SimpleDateFormat timeDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat timedate = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat format = new SimpleDateFormat("HH:mm");
        SimpleDateFormat time = new SimpleDateFormat("HH:mm:ss");
        Date date = new Date();

        HLInsurance hlInsurance = new HLInsurance();
        hlInsurance.setDataSourceCode("AUIS_ABE");//数据来源
        hlInsurance.setTransferType("TKTS");//传输类型
        hlInsurance.setFomerOrderId(timeToStamp());//业务方系统订单号
        hlInsurance.setOperator("hrb888b");//操作人
        hlInsurance.setOperationDate(timedate.format(new Date()));//操作日期
        hlInsurance.setOperationTime(time.format(new Date()));//操作时间
        BankReconciliation bankReconciliation = new BankReconciliation();
        bankReconciliation.setPaymentCode("YEEPAY_FENZHAN");//支付代码
        bankReconciliation.setPaymentSerialNumber("q1");//支付流水号
        bankReconciliation.setPaymentAmount(insuranceType.getPrice().toString());//支付金额
        String parse;
        try {
            parse = timeDate.format(new Date());
        } catch (Exception e){
            throw new Exception("日期转换错误");
        }
        bankReconciliation.setPaymentTime(parse);//支付时间
        InsuranceInfo insuranceInfo = new InsuranceInfo();
        PolicyHolder policyHolder = new PolicyHolder();
        policyHolder.setHolderName("北京金色世纪商旅网络科技股份有限公司");//投保人姓名
        policyHolder.setHolderIdType("BL");//投保人证件类型
        policyHolder.setHolderId("91110105582501947J");//投保人证件号码
        policyHolder.setHolderPhone("010-84926666");//投保人联系电话
        PolicyInsured policyInsured = new PolicyInsured();
        PolicyBeneficiary policyBeneficiary = new PolicyBeneficiary();
        policyInsured.setInsuredName(customer.getCustomerName());//被保人姓名
        policyInsured.setInsuredIdType(documents(customer.getIdType()).getAirline());//被保人证件类型
        policyInsured.setInsuredId(customer.getCustCertificateNo());//被保人证件号码
        policyInsured.setInsuredPhone(customer.getContractPhoneOne());//被保人联系电话
        policyBeneficiary.setBeneficiaryType("4");//受益人类型
        List<InsuranceLists> insuranceLists = new ArrayList<>();
        InsuranceLists lists = new InsuranceLists();
        Insurance insurance = new Insurance();
        insurance.setSerialNumber(SysUtils.getUuid().replaceAll("-", ""));//保险序列号
        insurance.setOperateSerialNumber(SysUtils.getUuid().replaceAll("-", ""));//保险操作序列号
        Product product = new Product();
        product.setProductCode(insuranceType.getProduct());//产品代码

        int count = Integer.parseInt(timeDate.format(date).substring(8, 10)) + 1;
        String tmpCount = String.valueOf(count);
        if (tmpCount.length() == 1){
            tmpCount = "0" + tmpCount;
        }

        String insuranceStartDate = timeDate.format(date).substring(0, 8) + tmpCount + " 00:00:00";
        insuranceStartDate = insuranceStartDate.replace("-", "");
        insuranceStartDate = insuranceStartDate.replace(" ", "");
        insuranceStartDate = insuranceStartDate.replace(":", "");

        product.setInsuranceStartDate(insuranceStartDate);//保险起期

        int parseInt = Integer.parseInt(timeDate.format(date).substring(0, 4));
        parseInt = parseInt + 1;
        String insuranceEndDate = parseInt + timeDate.format(date).substring(4, 10) + " 23:59:59";
        insuranceEndDate = insuranceEndDate.replace("-", "");
        insuranceEndDate = insuranceEndDate.replace(" ", "");
        insuranceEndDate = insuranceEndDate.replace(":", "");

        product.setInsuranceEndDate(insuranceEndDate);//保险止期
        insurance.setProduct(product);//产品信息
        InsuranceItem insuranceItem = new InsuranceItem();
        AuisAbe auisAbe = new AuisAbe();
        auisAbe.setAgentNo("pek602c");//代理人编号
        auisAbe.setTicketPrice("1000.0");//机票价格
        auisAbe.setReissueFlag("0");//改签标记
        auisAbe.setAirlineNo("867");//航空公司编号
        auisAbe.setEticketNo(timeToStamp());//电子客票号
        auisAbe.setBaggageNo("5");//行李险单号
        auisAbe.setTicketType("ARL-D");//机票类型
        auisAbe.setCarrier("LT");//承运人
        auisAbe.setFlightNo("LT4329");//航班号
        auisAbe.setDepartureAirportCode("HRB");//起飞机场三字码
        auisAbe.setArriveAirportCode("ZUH");//到达机场三字码

        auisAbe.setFlightDate(insuranceStartDate.substring(0, 8));//航班日期
        auisAbe.setFlightTime("000000");//航班时间
        insuranceItem.setAuisAbe(auisAbe);//保险专有字段
        lists.setInsurance(insurance);//保险信息
        lists.setInsuranceItem(insuranceItem);//保险专有字段
        insuranceLists.add(lists);
        insuranceInfo.setPolicyHolder(policyHolder);//投保人信息
        insuranceInfo.setPolicyInsured(policyInsured);//被保人信息
        insuranceInfo.setPolicyBeneficiary(policyBeneficiary);//受益人信息
        insuranceInfo.setInsuranceLists(insuranceLists);//保险产品信息
        InvoiceDelivery invoiceDelivery = new InvoiceDelivery();
        invoiceDelivery.setIsDelivery("0");//是否配送
        hlInsurance.setBankReconciliation(bankReconciliation);//对账信息
        hlInsurance.setInsuranceInfo(insuranceInfo);//开保相关人员信息
        hlInsurance.setInvoiceDelivery(invoiceDelivery);//发票配送信息
        return hlInsurance;
    }

    /**
     * 航联
     * */
    public Auis hanglianUtils(HLInsurance hlInsurance) throws Exception {
        HanglianUtils hanglianUtils = new HanglianUtils();
        Auis auis = hanglianUtils.openInsurance(hlInsurance);
        return auis;
    }

    /**
     * 德付通参数赋值（随票）
     * */
    public BuyInsuranceInput buyPolicyNoPay(ProductVo productVo, InsuranceType insuranceType) throws Exception {
        List<BuyInsuranceInfo> buyInsuranceInfoList = new ArrayList<>();
        BuyInsuranceInfo buyInsuranceInfo = new BuyInsuranceInfo();
        buyInsuranceInfo.setProtectName(productVo.insuredName);//被保人姓名
        buyInsuranceInfo.setProtectCard(productVo.insuredId);//被保人证件号码
        try {
            buyInsuranceInfo.setProtectIdType(documents(productVo.insuredIdType).getDove());//被保人证件类型，格式：身份证/护照----I/P（暂时只支持两种格式）
        } catch (Exception e){
            throw new Exception(e.getMessage());
        }

        buyInsuranceInfo.setProtectBirthday(productVo.beInsuredBirthday);//被保人生日，格式：yyyyMMdd做保险
        buyInsuranceInfo.setProtectPhone(productVo.insuredPhone);//被保人手机号
        buyInsuranceInfo.setTicketNo(productVo.ticketNo);//被保人票号13位去掉-
        buyInsuranceInfo.setFlightIndex(productVo.flightIndex);//被保人票号对应的航班序号
        buyInsuranceInfo.setFlightNo(productVo.flightNo);//航班号
        buyInsuranceInfo.setDepCity(productVo.depCity);//出发城市三字码
        buyInsuranceInfo.setArrCity(productVo.arrCity);//到达三字码
        buyInsuranceInfo.setDepDateTime(productVo.flightDate);//航班起飞时间
        buyInsuranceInfoList.add(buyInsuranceInfo);

        BuyInsuranceInput buyInsuranceInput = new BuyInsuranceInput();
        buyInsuranceInput.setInsuranceType(Integer.parseInt(insuranceType.getProduct()));//保险产品类型
        buyInsuranceInput.setBuyInsuranceInfos(buyInsuranceInfoList);//被保人详细信息
        return buyInsuranceInput;
    }

    /**
     * 德付通
     * */
    public BuyInsuranceOutput buyInsurance(BuyInsuranceInput buyInsuranceInput) {
        DovePayUtils dovePayUtils = new DovePayUtils();
        BuyInsuranceOutput buyInsuranceOutput = dovePayUtils.buyInsurance(buyInsuranceInput);
        return buyInsuranceOutput;
    }

    /**
     * 鼎盛参数赋值
     * */
    public HeyDayInsuranceVo heydayParameter(ProductVo productVo, Customer customer){
        HeyDayInsuranceVo heyDayInsuranceVo = new HeyDayInsuranceVo();
        heyDayInsuranceVo.setStartTime(productVo.flightDate + " " + productVo.flightTime);
        heyDayInsuranceVo.setArriveTime(productVo.arriveTime);
        heyDayInsuranceVo.setStartPosition(productVo.startPosition);
        heyDayInsuranceVo.setDestination(productVo.destination);
        heyDayInsuranceVo.setTransportNum(productVo.flightNo);
        heyDayInsuranceVo.setPhName(customer.getCustomerName());
        heyDayInsuranceVo.setPhIdType(customer.getIdType());
        heyDayInsuranceVo.setPhIdNo(customer.getCustCertificateNo());
        heyDayInsuranceVo.setPhPhone(customer.getContractPhoneOne());
        heyDayInsuranceVo.setPhEmail(productVo.phEmail);

        /*--------------------一下参数为非必传-----------------------------------------*/

        if (productVo.relation != null){
            heyDayInsuranceVo.setRelation(productVo.relation);
        }
        if (productVo.insuredName != null){
            heyDayInsuranceVo.setInsuredName(productVo.insuredName);
        }
        if (productVo.insuredIdType != null){
            heyDayInsuranceVo.setIdType(productVo.insuredIdType);
        }
        if (productVo.insuredId != null){
            heyDayInsuranceVo.setIdNo(productVo.insuredId);
        }
        if (productVo.insuredPhone != null){
            heyDayInsuranceVo.setPhone(productVo.insuredPhone);
        }
        if (productVo.email != null){
            heyDayInsuranceVo.setEmail(productVo.email);
        }

        return heyDayInsuranceVo;
    }

    /**
     * 鼎盛
     * */
    public String HeydayInsurance(String type, HeyDayInsuranceVo heyDayInsuranceVo) throws Exception {
        HeydayUtils heydayUtils = new HeydayUtils();
        HeydayUrlInfo heydayUrlInfo;
        try {
            heydayUrlInfo = heydayUtils.heydayInsurance(type);
        } catch (Exception e){
            throw new Exception(e.getMessage());
        }

        String json = JSONArray.toJSON(heyDayInsuranceVo).toString();

        String encode = null;
        try {
            encode = URLEncoder.encode(json, "utf-8");
        } catch (Exception e){
            System.out.println("encodeURI转码失败");
        }

        if (heydayUrlInfo.getUrl() != null && encode != null){
            String url = heydayUrlInfo.getUrl() + "&extend=" + encode;
            return url;
        }
        else {
            return null;
        }
    }

    /**
     * 航联定时任务开保
     * */
    @Override
    public boolean hangLianOpenInsurance(Long customerId, ProductVo productVo) throws Exception {
        boolean flag = false;
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();
        //获取会员信息
        if (customerId == null || customerId == 0){
            throw new Exception("会员id不能为空");
        }
        Customer customer = customerMapper.selectCustomerById(customerId);
        if (customer == null){
            throw new Exception("无效的会员id");
        }

        //获取辅营产品信息
        if (productVo.id == null || productVo.id == 0){
            throw new Exception("辅营产品id不能为空");
        }
        AssistProduct assistProduct = assistProductMapper.selectProduct(productVo.id);
        if (assistProduct == null){
            throw new Exception("无效的辅营产品id");
        }

        //获取产品类型
        if (assistProduct.getProductTypeid() == null || assistProduct.getProductTypeid() == 0){
            throw new Exception("辅营产品对应产品类型ID不能为空");
        }
        InsuranceType insuranceType = insuranceTypeMapper.selectInsuranceTypeById(assistProduct.getProductTypeid());
        if (insuranceType == null){
            throw new Exception("无效的产品类型id");
        }

        if (insuranceType.getCompanyId() == null || insuranceType.getCompanyId() == 0){
            throw new Exception("产品类型对应保险公司id不能为空");
        }
        if (insuranceType.getInsTypeCode() == null || insuranceType.getInsTypeCode().equals("")){
            throw new Exception("产品类型代码不能为空");
        }

        //航联参数赋值
        HLInsurance hlInsurance = hanglianParameter(productVo, customer, insuranceType);
        //航联开保
        Auis auis = hanglianUtils(hlInsurance);

        InsuranceRecord insuranceRecord = new InsuranceRecord();
        insuranceRecord.setCustomerCard(productVo.cardNum);
        insuranceRecord.setReturnData(auis.toString());
        insuranceRecord.setBatch(auis.getRequestId());
        insuranceRecord.setInsTypeId(assistProduct.getProductTypeid());
        insuranceRecord.setCustomerId(customerId);
        insuranceRecord.setEmployeeId(10l);
        insuranceRecord.setInsCoId(insuranceType.getCompanyId());
        insuranceRecord.setIdTypeId(customer.getIdType());
        insuranceRecord.setInsCoverName(format.format(date));

        int count = Integer.parseInt(format.format(date).substring(8, 10)) + 1;
        String tmpCount = String.valueOf(count);
        if (tmpCount.length() == 1){
            tmpCount = "0" + tmpCount;
        }

        String insuranceStartDate = format.format(date).substring(0, 8) + tmpCount + " 00:00:00";

        insuranceRecord.setInsValidDate(format.parse(insuranceStartDate));

        int parseInt = Integer.parseInt(format.format(date).substring(0, 4));
        parseInt = parseInt + 1;
        String insuranceEndDate = parseInt + format.format(date).substring(4, 10) + " 23:59:59";

        insuranceRecord.setInsInvalidDate(format.parse(insuranceEndDate));
        insuranceRecord.setInsured(customer.getCustomerName());
        insuranceRecord.setBeneficiary(customer.getCustomerName());
        if (auis.getResultCode().equals("000000")){
            insuranceRecord.setInsMemo("已开通成功");
            insuranceRecord.setHLurl(auis.getResponseData().getPolicyInfo().getEPolicyUrl());
            insuranceRecord.setOpenState(InsuranceTypeEnum.Open.getValue());
        }
        else {
            insuranceRecord.setInsMemo("开通失败");
            insuranceRecord.setOpenState(InsuranceTypeEnum.FailedToActivate.getValue());
        }
        if (auis.getResponseData() != null && auis.getResponseData().getPolicyInfo() != null){
            insuranceRecord.setInsSlipNo(auis.getResponseData().getPolicyInfo().getPolicyNo());
        }
        insuranceRecord.setOperationTime(format.format(date));
        insuranceRecord.setInsCertificateNo(customer.getCustCertificateNo());
        insuranceRecord.setMobilephone(customer.getContractPhoneOne());
//        insuranceRecord.setOpenState(InsuranceTypeEnum.Open.getValue());
        insuranceRecord.setOrderNum(productVo.orderNum);
        insuranceRecord.setOrderSource(productVo.orderSource);
        insuranceRecord.setGuaranteeId(productVo.guaranteeId);
        int record = insuranceRecordMapper.insertInsuranceRecord(insuranceRecord);
        if (record > 0){
            flag = true;
        }

        return flag;
    }

    /**
     * 修改德付通保险状态（远程）
     * */
    @Override
    public int updateStart(InsuranceRecord insuranceRecord) {
        int i = insuranceRecordMapper.updateStart(insuranceRecord);
        return i;
    }

    @Override
    public InsuranceRecord getInuseranceRecord(Long recordId)
    {
        InsuranceRecord insuranceRecord = insuranceRecordMapper.selectInsuranceRecord(recordId);
        if (!StringHelper.isNullOrEmpty(insuranceRecord.getBatch()))
        {
            ProductVo productVo = JSON.parseObject(insuranceRecord.getBatch(), ProductVo.class);
            insuranceRecord.setProductVo(productVo);
        }
        return insuranceRecord;
    }

    /**
     * 证件类型
     * */
    public DocumentsVo documents(String type) throws Exception {
        DocumentsVo documentsVo = new DocumentsVo();
        if (type != null && !type.equals("")){
            switch (type){
                case "ID_CARD"://身份证
                    documentsVo.setAirline(InsuranceTypeEnum.Airline_ID_CARD.getValue());
                    documentsVo.setDove(InsuranceTypeEnum.Dove_ID_CARD.getValue());
                    documentsVo.setHeyday(InsuranceTypeEnum.HeyDay_ID_CARD.getValue());
                    break;
                case "PASSPORT"://护照
                    documentsVo.setAirline(InsuranceTypeEnum.Airline_PASSPORT.getValue());
                    documentsVo.setDove(InsuranceTypeEnum.Dove_PASSPORT.getValue());
                    documentsVo.setHeyday(InsuranceTypeEnum.HeyDay_ID_CARD.getValue());
                    break;
                case "MILITARY_ID"://军官证
                    documentsVo.setAirline(InsuranceTypeEnum.Airline_MILITARY_ID.getValue());
                    documentsVo.setHeyday(InsuranceTypeEnum.HeyDay_otherDocuments.getValue());
                    break;
                case "MTPFHKAMR"://回乡证
                case "MTPFTR"://回乡证
                    documentsVo.setAirline(InsuranceTypeEnum.Airline_MTPFTR.getValue());
                    documentsVo.setHeyday(InsuranceTypeEnum.HeyDay_otherDocuments.getValue());
                    break;
                case "RPFHKMATR"://台胞证
                    documentsVo.setAirline(InsuranceTypeEnum.Airline_RPFHKMATR.getValue());
                    documentsVo.setHeyday(InsuranceTypeEnum.HeyDay_otherDocuments.getValue());
                    break;
                case "HKAMP"://港澳通行证
                    documentsVo.setAirline(InsuranceTypeEnum.Airline_HKAMP.getValue());
                    documentsVo.setHeyday(InsuranceTypeEnum.HeyDay_otherDocuments.getValue());
                    break;
                case "ACCOUNT_BOOK"://户口簿
                    documentsVo.setAirline(InsuranceTypeEnum.Airline_ACCOUNT_BOOK.getValue());
                    documentsVo.setHeyday(InsuranceTypeEnum.HeyDay_otherDocuments.getValue());
                    break;
                case "BIRTH_CERTIFICATE"://出生证明
                    documentsVo.setAirline(InsuranceTypeEnum.Airline_BIRTH_CERTIFICATE.getValue());
                    documentsVo.setHeyday(InsuranceTypeEnum.HeyDay_otherDocuments.getValue());
                    break;
                case "OTHER_DOCUMENTS"://其他
                    documentsVo.setAirline(InsuranceTypeEnum.Airline_otherDocuments.getValue());
                    documentsVo.setHeyday(InsuranceTypeEnum.HeyDay_otherDocuments.getValue());
                    break;
                case "ORGANIZATION_CODE"://组织机构代码
                    documentsVo.setAirline(InsuranceTypeEnum.Airline_otherDocuments.getValue());
                    documentsVo.setAirline(InsuranceTypeEnum.HeyDay_Organization_Code.getValue());
                    break;
                case "BUSINESS_LICENSE"://营业执照
                    documentsVo.setAirline(InsuranceTypeEnum.Airline_otherDocuments.getValue());
                    documentsVo.setAirline(InsuranceTypeEnum.HeyDay_Business_License.getValue());
                    break;
                case "UN_DOCUMENTED"://无证件
                    throw new Exception("该会员目前没有添加证件");
            }
        }
        else {
            throw new Exception("证件类型不能为空");
        }
        return documentsVo;
    }

    /**
     * 获取时间戳yyyy-MM-dd HH:mm:ss SS
     * */
    public String timeToStamp() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SS");
        String res;
        Date time = new Date();
        String s = simpleDateFormat.format(time);
        Date date = null;
        try {
            date = simpleDateFormat.parse(s);
        } catch (Exception e){
            System.out.println("时间转换失败");
        }

        long ts = date.getTime();
        res = String.valueOf(ts);
        return res;
    }











}
